package com.mng.transform;

import com.mng.dto.SensorReading;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class KeyStreamTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> stringDataStream = env.readTextFile("src/main/resources/wc.txt");
        env.readTextFile("src/main/resources/wc.txt");

        DataStream<SensorReading> sensorReadingDataStream = stringDataStream.flatMap(new FlatMapFunction<String, SensorReading>() {

            @Override
            public void flatMap(String s, Collector<SensorReading> collector) throws Exception {
                String[] strings = s.split(",");
                String id = strings[0];
                Long timestamp = Long.parseLong(strings[1]);
                Double temp = Double.parseDouble(strings[2]);
                collector.collect(new SensorReading(id,timestamp,temp));
            }
        });
        KeyedStream<SensorReading, String> sensorReadingStringKeyedStream = sensorReadingDataStream.keyBy(sensorReading -> sensorReading.getId());
        DataStream<SensorReading> sKey1 = sensorReadingStringKeyedStream.reduce(
                new ReduceFunction<SensorReading>() {
                    @Override
                    public SensorReading reduce(SensorReading sensorReading, SensorReading t1) throws Exception {
                        t1.setTemperaturre(Math.max(sensorReading.getTemperaturre(),t1.getTemperaturre()));
                        return t1;
                    }
                }
        );
        sKey1.print("result");
        env.execute();
    }
}
